package com.levi.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 注册消费监听器，消费消息后有返回值，保证消息可靠消费
 * 返回sucess说明消费成功，返回later说明消费失败，消费失败后会进行重试，默认重试16次，超过重试次数之后会把消息打入死信队列
 *
 */
@Component
@Slf4j
public class MQConsumer {

    @Value("${rocketmq.consumer.group}")
    private String consumerGruop;//读取配置文件的消费者

    @Value("${rocketmq.name-server}")
    private String namesrvAddr;//从配置文件读取nameserver

    //提供一个空的构造器
    public MQConsumer(){

    }
    //提供默认的消费者
    @PostConstruct
    public void defaultMQConsumer() throws MQClientException {
        //1:指定消费者 所消费的主题(队列) 和tag(2级标签,用于过滤消息)
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(consumerGruop);//从消费组拿到1个消费者
        //说明：如果要消费所有tag，用通配符*代替所有tag，如果明确指定则更改*为某个tag
        consumer.subscribe("orderTopic","*");
        //2:指定消费的策略(从所有的消息开头位置执行，还是从消息的尾部执行)指定消费的顺序
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        //TODO ....消费者lambda
        consumer.registerMessageListener((MessageListenerConcurrently) (list, context) -> {//注册消息监听器，用的lambda
            try {
                for (MessageExt messageExt : list) {
                    String messageBody = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);//读取远程配置的编码为utf-8
                    System.out.println("messageExt: " + messageExt);//输出消息内容
                    System.out.println("消费响应：msgId : " + messageExt.getMsgId() + ",  msgBody : " + messageBody);//输出消息内容
                    //重新发送次数超过3次的消息将不再进行重试,直接保存到DB,进行人工处理
                    if (messageExt.getReconsumeTimes()== 3 ){
                        //对消息进行入库
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ConsumeConcurrentlyStatus.RECONSUME_LATER; //消费失败,稍后再试
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; //消费成功
        });


        //3:开启监听 消息消费
        consumer.start();
    }
}
